package b1.scenes
{
	import b1.conifg.*;
	import b1.conifg.story.*;
	import b1.controls.basic.*;
	import b1.net.*;
	import b1.players.*;
	import b1.scenes.fight.*;
	import b1.scenes.home.*;
	import b1.scenes.tower.Tower;
	import b1.utils.*;
	
	import com.greensock.TweenLite;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.media.Sound;
	
	public class StoryHelper
	{
		static private var instance:StoryHelper;
		//是否处于故事模式
		public var storyModeFlag:Boolean;
		public var specialCase:SpecialCaseConfig;
		public var stepIndex:int;
		private var stepConfig:StepConfig;
		//在切换家的时候需要清空的所有元素
		private var elementsToClearWhenSwitchHome:Array;
		//上一步骤的所有元素
		private var lastStepElements:Array;
		//门动画
		private var gateMovie:BasicMc;
		//播放关门动画结束标志
		private var reverseGateMovieCompleteFlag:Boolean;
		//最后回家结束标志
		private var finalSwitchHomeCompleteFlag:Boolean;
		//记录播放过的影片剪辑
		private var playedMcFlag:Object;
		
		public function StoryHelper()
		{
			storyModeFlag = false;
			stepIndex = -1;
			lastStepElements = new Array();
			elementsToClearWhenSwitchHome = new Array(); 
			playedMcFlag = new Object();
		}

		static public function getInstance():StoryHelper
		{
			if (!instance)
				instance = new StoryHelper();
			return instance;
		}
		
		//开始故事模式
		public function startStory(specialCase:SpecialCaseConfig):void
		{
			storyModeFlag = true;
			this.specialCase = specialCase;
			stepIndex = -1;
			nextStep();
			playGateMovie();
			//刷新用户顺序
			BottomNavigator.getInstance().refreshFriends();
		}
		
		//结束故事模式
		public function endStory():void
		{
			clearElementsOnSwitchHome();
			clearLastStepElements();
			SceneContainer.getInstance().mouseDisableFlag = false;
			storyModeFlag = false;
			specialCase = null;
			stepIndex = -1;
			lastStepElements = new Array();
			reversePlayGateMovie();
			finalSwitchHomeCompleteFlag = false;
			ServerHelper.getInstance().addEventListener(ServerEvent.SWITCH_HOME_COMPLETE, onFinalSwitchHomeComplete);
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			home.switchLiveId(PlayerInfoHelper.getInstance().userId, true);
		}
		
		//播放门动画
		public function playGateMovie():void
		{
			var GateMovie:Class = ResourceHelper.getInstance().getClassByName("GateMovie");
			gateMovie = new BasicMc(GateMovie, 60, false);
			gateMovie.eventDispatcher.addEventListener(BasicMc.ON_MOVIE_FINISH, onGateMovieFinish);
			SceneContainer.getInstance().currentScene.addChild(gateMovie);
			//播放音效
			var SoundDoor1:Class = ResourceHelper.getInstance().getClassByName("SoundDoor1");
			var sound:Sound = new SoundDoor1();
			sound.play(); 
		}
		
		private function onGateMovieFinish(event:Event):void
		{
			gateMovie.eventDispatcher.removeEventListener(BasicMc.ON_MOVIE_FINISH, onGateMovieFinish);
			if (gateMovie.parent != null)
				gateMovie.parent.removeChild(gateMovie); 
			nextStep();
		} 
		
		//在故事模式下进入下一步
		public function nextStep():void
		{
			if (!storyModeFlag)
				return;
			stepConfig = specialCase.steps[stepIndex + 1];
			if (!checkPremises(stepConfig))
				return;
			doCommonStep(stepConfig);
			stepIndex++;
			switch (stepConfig.type)
			{
				//说话
				case 0:
					speak(stepConfig as SpeakConfig);
					break;
				//帮助箭头
				case 1:
					launchArrowHelper(stepConfig as ArrowHelperConfig);
					break;
				//开始战斗
				case 2:
					startFight(stepConfig as FightConfig);
					break;
				//操作控件
				case 3:
					manipulateControl(stepConfig as ControlConfig);
					break;
				//切换家
				case 4:
					switchHome(stepConfig as SwitchHomeConfig);
					break;
				//完成任务
				case 5:
					accomplishTask(stepConfig as AccomplishTaskConfig);
					break;
				//移动动物
				case 6:
					moveAnimal(stepConfig as AnimalMoveConfig);
					break;
				//逮捕动物
				case 7:
					arrestAnimal(stepConfig as ArrestConfig);
					break;
				//播放影片剪辑
				case 8:
					playMovieClip(stepConfig as PlayMovieClipConfig);
					break;
				//魔塔
				case 9:
					startTower(stepConfig as TowerConfig);
					break;
				default:
			}
			if (stepConfig.autoNextStep)
				nextStep();
		}
		
		//步骤共同的操作
		public function doCommonStep(stepConfig:StepConfig):void
		{
			if (stepConfig.clear)
				clearLastStepElements();
			SceneContainer.getInstance().mouseDisableFlag = stepConfig.mouseDisableFlag;
			SceneContainer.getInstance().targetPosX = stepConfig.targetPosX;
			SceneContainer.getInstance().targetPosY = stepConfig.targetPosY;
			if (stepConfig.soundName != "")
			{
				//播放音效
				var StepSound:Class = ResourceHelper.getInstance().getClassByName(stepConfig.soundName);
				var sound:Sound = new StepSound();
				sound.play(); 
			}
		}
		
		//清除上一步的所有控件
		public function clearLastStepElements():void
		{
			var lastStepElement:Object = lastStepElements.pop();
			while (lastStepElement != null)
			{
				if (lastStepElement.parent != null)
				{
					lastStepElement.parent.removeChild(lastStepElement);
				}
				lastStepElement = lastStepElements.pop();
			}
		} 
		
		//清除应该在切换家完成时清空的控件
		public function clearElementsOnSwitchHome():void
		{
			var element:Object = elementsToClearWhenSwitchHome.pop();
			while (element != null)
			{
				if (element.parent != null)
				{
					element.parent.removeChild(element);
				}
				element = elementsToClearWhenSwitchHome.pop();
			}
		} 
		
		//检查所有前提条件
		private function checkPremises(stepConfig:StepConfig):Boolean
		{
			if (stepConfig.checkLiveId != 0)
			{
				return checkLiveId(stepConfig.checkLiveId);
			}
			return true;
		}
		
		//检查当前的家住址
		private function checkLiveId(liveId:int):Boolean
		{
			if (SceneContainer.getInstance().currentScene is Home)
			{
				var home:Home = SceneContainer.getInstance().currentScene as Home;
				if (home.liveId == liveId)
					return true;
			}
			return false;
		}
		
		//说话
		private function speak(speakConfig:SpeakConfig):void
		{
			var speakMessageBox:MessageBoxWithIcon = new MessageBoxWithIcon(speakConfig.content, speakConfig.talkerImage, speakConfig.talkerName);
			speakMessageBox.x = BFont.stageWidth / 2;
			speakMessageBox.y = BFont.stageHeight / 2;
			TweenLite.from(speakMessageBox, 0.2, {x:speakConfig.messageBoxStartPosX, y:speakConfig.messageBoxStartPosY, scaleX:0.1, scaleY:0.1, onComplete:onSpeakFinish});
			SceneContainer.getInstance().currentScene.addChild(speakMessageBox);
			lastStepElements.push(speakMessageBox);
			//播放音效
			var SoundDialog1:Class = ResourceHelper.getInstance().getClassByName("SoundDialog1");
			var sound:Sound = new SoundDialog1();
			sound.play();
		}
		
		private function onSpeakFinish():void
		{
			//添加新手导引
			if (SceneContainer.getInstance().step == 11 || SceneContainer.getInstance().step == 12 
			|| SceneContainer.getInstance().step == 13 || SceneContainer.getInstance().step == 14 
			|| SceneContainer.getInstance().step == 15 || SceneContainer.getInstance().step == 16
			|| SceneContainer.getInstance().step == 28 || SceneContainer.getInstance().step == 29
			|| SceneContainer.getInstance().step == 30 || SceneContainer.getInstance().step == 31)
			{
				SceneContainer.getInstance().addStep();
			}
		}
		
		//帮助箭头
		private function launchArrowHelper(arrowHelperConfig:ArrowHelperConfig):void
		{
			var arrowHelper:ArrowHelper = new ArrowHelper(arrowHelperConfig.direction, arrowHelperConfig.content, arrowHelperConfig.dialogWidth, arrowHelperConfig.dialogHeight);
			arrowHelper.x = arrowHelperConfig.posX;
			arrowHelper.y = arrowHelperConfig.posY;
			SceneContainer.getInstance().currentScene.addChild(arrowHelper);
			lastStepElements.push(arrowHelper);
		}
		
		//开始战斗
		private function startFight(fightConfig:FightConfig):void
		{
			//本人信息
			var userId:int = PlayerInfoHelper.getInstance().userId;
			var userInfo:PlayerInfo = PlayerInfoHelper.getInstance().players[userId];
			var userAnimalId:int = userInfo.ownAnimals[0];
			//对手信息
			var opponentAnimal:AnimalInfo = PlayerInfoHelper.getInstance().animals[fightConfig.opponentAnimalId];
			var fight:Fight = new Fight(userId, opponentAnimal.ownerId, [userAnimalId], [fightConfig.opponentAnimalId], onFightComplete, fightConfig);
			SceneContainer.getInstance().loadScene(fight);
		}
		
		//战斗结束回调
		private function onFightComplete(leftPlayerId:int, rightPlayerId:int, winnerAnimalId:int, loserAnimalId:int, caseBones:int, loseHeirloomId:String, 
			animalCluesDrop:Object, fightConfig:FightConfig, newHonours:Object):void
		{
			var me:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
			if (fightConfig.failTaskFlag && winnerAnimalId != parseInt(me.ownAnimals[0]))
			{
				storyModeFlag = false;
				SceneContainer.getInstance().mouseDisableFlag = true;
				SceneContainer.getInstance().targetPosX = 352.2;
				SceneContainer.getInstance().targetPosY = 345.95;
				var helperMessageBox:MessageBoxWithIcon = new MessageBoxWithIcon("任务失败！self 探长不要灰心，请回去休整之后再来！", "id:-5", Config.assistantName);
				helperMessageBox.x = BFont.stageWidth / 2;
				helperMessageBox.y = BFont.stageHeight  / 2;
				helperMessageBox.buttonOK.addEventListener(MouseEvent.CLICK, onFailButtonOKClick);
				SceneContainer.getInstance().currentScene.addChild(helperMessageBox);
			}
			else
			{
				nextStep();
			}			
		}
		
		//失败界面确定按钮相应
		private function onFailButtonOKClick(event:MouseEvent):void
		{
			endStory();	
		}
		
		//操作控件
		private function manipulateControl(controlConfig:ControlConfig):void
		{
			var actionIndex:int = controlConfig.actionIndex;
			switch (controlConfig.controlName)
			{
				case "BottomNavigator":
				if (actionIndex == 0)
					BottomNavigator.getInstance().extend();
				else
					BottomNavigator.getInstance().hide();
				break;
			}
		}
		
		//切换家
		private function switchHome(switchHomeConfig:SwitchHomeConfig):void
		{
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			if (switchHomeConfig.liveId == "self")
				home.switchLiveId(PlayerInfoHelper.getInstance().userId, switchHomeConfig.force);
			else
				home.switchLiveId(parseInt(switchHomeConfig.liveId), switchHomeConfig.force);
		}

		//播放关门动画
		public function reversePlayGateMovie():void
		{
			reverseGateMovieCompleteFlag = false;
			var GateMovie:Class = ResourceHelper.getInstance().getClassByName("GateMovie");
			gateMovie = new BasicMc(GateMovie, -60, false);
			gateMovie.eventDispatcher.addEventListener(BasicMc.ON_MOVIE_FINISH, onReverseGateMovieFinish);
			SceneContainer.getInstance().currentScene.addChild(gateMovie);
			//播放音效
			var SoundDoor1:Class = ResourceHelper.getInstance().getClassByName("SoundDoor1");
			var sound:Sound = new SoundDoor1();
			sound.play(); 
		}
		
		//播放关门动画完毕
		private function onReverseGateMovieFinish(event:Event):void
		{
			gateMovie.eventDispatcher.removeEventListener(BasicMc.ON_MOVIE_FINISH, onGateMovieFinish);
			reverseGateMovieCompleteFlag = true;
			if (gateMovie.parent != null)
				gateMovie.parent.removeChild(gateMovie);
			if (finalSwitchHomeCompleteFlag)
				sendAccomplishTask(); 
		} 
		
		//最后的回家刷新完毕
		private function onFinalSwitchHomeComplete(event:Event):void
		{
			ServerHelper.getInstance().removeEventListener(ServerEvent.SWITCH_HOME_COMPLETE, onFinalSwitchHomeComplete);
			finalSwitchHomeCompleteFlag = true;
			if (reverseGateMovieCompleteFlag)
				sendAccomplishTask();
		}
		
		//向服务器发送完成任务
		private function sendAccomplishTask():void
		{
			if (this.stepConfig is AccomplishTaskConfig)
			{
				var accomplishTaskConfig:AccomplishTaskConfig = this.stepConfig as AccomplishTaskConfig;
				ServerHelper.getInstance().accomplishTask(accomplishTaskConfig.taskType, accomplishTaskConfig.taskId);
				stepConfig = null;
			}
		}
		
		//完成任务
		private function accomplishTask(accomplishTaskConfig:AccomplishTaskConfig):void
		{
			endStory();
		}
		
		//逮捕动物
		private function arrestAnimal(arrestConfig:ArrestConfig):void
		{
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			home.startArrestAnimalMovie(arrestConfig.animalId);
		}
		
		//移动动物
		private function moveAnimal(animalMoveConfig:AnimalMoveConfig):void
		{
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			var McClass:Class = ResourceHelper.getInstance().getClassByName(animalMoveConfig.animalIdStr);
			if (McClass != null)
			{
				var targetMc:BasicMc = new BasicMc(McClass);
				targetMc.x = animalMoveConfig.startPosX;
				targetMc.y = animalMoveConfig.stopPosY;
				targetMc.scaleX = animalMoveConfig.scaleX;
				elementsToClearWhenSwitchHome.push(targetMc);
				home.addChild(targetMc);
				TweenLite.to(targetMc, animalMoveConfig.duration, {x:animalMoveConfig.stopPosX, y:animalMoveConfig.stopPosY, rotation:animalMoveConfig.rotation, onComplete:onMoveAnimalFinish, onCompleteParams:[animalMoveConfig]});
			}
			else
			{
				var animalId:int;
				if (animalMoveConfig.animalIdStr == "self")
				{
					var me:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
					animalId = me.ownAnimals[0];
				}
				else
				{
					animalId = parseInt(animalMoveConfig.animalIdStr);
				}
				var animal:HomeAnimal;
				if (home.homeAnimals[animalId] == null)
				{
					animal = new HomeAnimal(animalId, home.liveId);
					home.animalContainer.addChild(animal);
					home.homeAnimals[animal.animalId] = animal;
					animal.x = animalMoveConfig.startPosX;
					animal.y = animalMoveConfig.startPosY;
				}
				else
				{
					animal = home.homeAnimals[animalId];
				}
				animal.animalMc.status = animalMoveConfig.startStatus;
				animal.stopWalk();
				animal.rotation = animalMoveConfig.rotation;
				TweenLite.to(animal, animalMoveConfig.duration, {x:animalMoveConfig.stopPosX, y:animalMoveConfig.stopPosY, rotation:animalMoveConfig.rotation, onComplete:onMoveAnimalFinish, onCompleteParams:[animalMoveConfig]});
			}
		}
		
		private function onMoveAnimalFinish(animalMoveConfig:AnimalMoveConfig):void
		{
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			var McClass:Class = ResourceHelper.getInstance().getClassByName(animalMoveConfig.animalIdStr);
			if (McClass == null)
			{
				var animalId:int;
				if (animalMoveConfig.animalIdStr == "self")
				{
					var me:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
					animalId = me.ownAnimals[0];
				}
				else
				{
					animalId = parseInt(animalMoveConfig.animalIdStr);
				}
				var animal:HomeAnimal = home.homeAnimals[animalId];
				animal.animalMc.status = animalMoveConfig.stopStatus;
			}
			nextStep();
		}
		
		//播放影片剪辑
		private function playMovieClip(playMovieClipConfig:PlayMovieClipConfig):void
		{
			if (playedMcFlag[playMovieClipConfig.className] == null)
			{
				//影片
				var MovieClipClass:Class = ResourceHelper.getInstance().getClassByName(playMovieClipConfig.className);
				var movie:BasicMc = new BasicMc(MovieClipClass, 20, false);
				movie.x = playMovieClipConfig.posX;
				movie.y = playMovieClipConfig.posY;
				lastStepElements.push(movie);
				SceneContainer.getInstance().currentScene.addChild(movie);
				movie.eventDispatcher.addEventListener(BasicMc.ON_MOVIE_FINISH, onPlayMovieClipComplete);
				playedMcFlag[playMovieClipConfig.className] = 1;
			}
			else
			{
				nextStep();
			}
		}
		
		//进入魔塔系统
		private function startTower(towerConfig:TowerConfig):void
		{
			var tower:Tower = Tower.getInstance();
			tower.loadConfig(towerConfig);
			tower.loadLayer(0);
			SceneContainer.getInstance().loadScene(tower);
		}
		
		//影片剪辑播放完毕响应
		private function onPlayMovieClipComplete(event:Event):void
		{
			nextStep();
		}
	}
}